import { rootState } from '@/types/store';
import { Input, NavBar, TextArea } from 'antd-mobile';
import { InputRef } from 'antd-mobile/es/components/input';
import { TextAreaRef } from 'antd-mobile/es/components/text-area';
import { useEffect, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import styles from './index.module.scss';
//定义组件的类型,否则那边传递不来参数
type Props = {
  hideInput: () => void;
  type: '' | 'name' | 'intro';
  Update: (key: string, value: string) => void;
};
const EditInput = ({ hideInput, type, Update }: Props) => {
  const flag = type === 'name' ? '昵称' : '简介';
  //从redux中获取用户数据
  const { profileUse } = useSelector((state: rootState) => state.profile);
  //输入框定义受控状态
  const [inputValue, setInputValue] = useState(
    type === 'name' ? profileUse.name : profileUse.intro
  );
  //进入页面,输入框自动获取焦点
  const inputRef = useRef<InputRef>(null);
  const inputText = useRef<TextAreaRef>(null);
  useEffect(() => {
    if (flag) {
      inputRef.current?.focus();
    }
    inputText.current?.focus();
    //获取原生方法
    document.querySelector('textarea')?.setSelectionRange(-1, -1);
  }, [flag]);
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={
          <span
            className="commit-btn"
            onClick={() => {
              type === 'name'
                ? Update('name', inputValue)
                : Update('intro', inputValue);
            }}
          >
            提交
          </span>
        }
        onBack={hideInput}
      >
        编辑{flag}
      </NavBar>

      <div className="edit-input-content">
        <h3>{flag}</h3>
        {flag === '昵称' ? (
          <div className="input-wrap">
            <Input
              placeholder="请输入"
              value={inputValue}
              ref={inputRef}
              onChange={(e) => {
                setInputValue(e);
              }}
            />
          </div>
        ) : (
          <div>
            <TextArea
              placeholder="请输入简介"
              showCount
              maxLength={100}
              value={inputValue || ''}
              className="textarea"
              ref={inputText}
              onChange={(e) => setInputValue(e)}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default EditInput;
